import iterateClassification
import layerClassification
from basic import *
from tu import *
import matplotlib.pyplot as plt


def err_bar(x, C1, C2):
    a = external_classes(C1)
    b = internal_classes(x, C1)**2
    c = external_classes(C2)
    d = internal_classes(x, C2)**2
    err_bar1 = (a / b + c / d) / 2
    return err_bar1


def process(solution):
    S = solution[0]
    M = solution[1]
    L = []
    L1 = [0]
    L2 = [0]
    L3 = []
    # min_err = err_bar(M[0], S[0][0], S[0][1])
    # where_min_err = 0
    # for i in range(len(S)):
    #     err_bar1 = err_bar(M[i], S[i][0], S[i][1])
    #     print("err_bar1:",err_bar1)
    #     if err_bar1 < min_err:
    #         min_err = err_bar1
    #         where_min_err = i
    #         print("min_err:",min_err)
    for i in range(len(S)):
        L.append(err_bar(M[i], S[i][0], S[i][1]))
    for i in range(1, len(L)):
        # L1.append(abs(L[i]-L[i-1]))
        L1.append(L[i]-L[i-1])
    for i in range(1, len(L1)):
        L2.append(abs(L1[i]-L1[i-1]))
        # L2.append(L1[i]-L1[i-1])
    mean = get_mean(L2)
    stdev = get_stdev(L2)
    has_found = 0
    pct = 50
    while pct>=1:
        for x in L2[1:]:
            if in_chebyshevs_interval(x, mean, stdev, pct)==0:
                L3.append(x)
        if len(L3) == 0:
            pct-=1
            print("NOW:",pct)
        else:
            has_found = 1
            break
    if has_found == 0:
        res = [flatten(S[0]), []]
    else:
        where = L2.index(L3[0])-1
        res = S[where]
    #print("L:",L)
    #print("L1:",L1)
    #print("L2:",L2)
    #print("L3:",L3)
    #min_l2 = max(L2)
    #print(L2.index(min_l2)-1)
    # # min_l2 = min(L2)
    
    # plt.subplot(2,2,1)
    # X_pos = [n for n in range(0,L.__len__())]
    # plt.plot(X_pos,L)
    # plt.subplot(2,2,2)
    # plt.plot(X_pos,L1)
    # plt.subplot(2,2,3)
    # plt.bar(X_pos, L2, 0.4, color="green")
    # plt.show()
    
    #return S[L2.index(min_l2)-1]
    return res
    # return S[where_min_err]